package com.zaker.touchtv.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class SystemUtils {

  @SuppressLint("SetJavaScriptEnabled")
  @SuppressWarnings("deprecation")
  public static void configWebBrowser(Context context, WebView webView, String path) {

    if (webView == null || context == null) {
      return;
    }

    WebSettings settings = webView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setSupportZoom(false);
    settings.setBuiltInZoomControls(false);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

      settings.setDisplayZoomControls(false);
    }
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {

      settings.setMediaPlaybackRequiresUserGesture(false);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
      settings.setAllowFileAccessFromFileURLs(true);
    }

    settings.setSaveFormData(false);
    settings.setAllowFileAccess(true);

    settings.setUseWideViewPort(true);
    settings.setLoadWithOverviewMode(true);
    settings.setDefaultTextEncodingName("utf-8");
//    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setAppCacheEnabled(false);
    settings.setSavePassword(false);
    settings.setDatabaseEnabled(true);
    settings.setDomStorageEnabled(true);
    settings.setGeolocationEnabled(true);

    if (!TextUtils.isEmpty(path)) {
      settings.setGeolocationDatabasePath(path);
    }

    settings.setCacheMode(WebSettings.LOAD_DEFAULT);
    CookieSyncManager.createInstance(context);
    CookieSyncManager.getInstance().startSync();

  }

  @SuppressWarnings("deprecation")
  public static void releaseWebBrowser(WebView webView) {

    if (webView != null) {
      Log.i("TEST", "releaseWebBrowser is run!");
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        webView.onResume();
      }
      webView.clearFormData();
      webView.clearSslPreferences();
      webView.clearHistory();
      webView.clearMatches();
      webView.setVisibility(View.GONE);
      webView.removeAllViews();
      webView.setWebViewClient(null);
      webView.setDownloadListener(null);
      webView.loadUrl("about:blank");
      webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
          super.onPageFinished(view, url);
          Log.i("TEST", "releaseWebBrowser is run 2 url: " + url);
          if (view != null) {
            view.stopLoading();
            view.freeMemory();
            view.destroy();
          }
        }
      });
    }

  }

}
